package com.zonhar.autofeed.common.device.hcsr04;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.extra.mail.MailUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pi4j.io.gpio.*;
import com.zonhar.autofeed.common.device.camera.CameraDevice;
import com.zonhar.autofeed.common.util.RedisUtil;
import com.zonhar.autofeed.cron.Hcsr04Cron;
import com.zonhar.autofeed.entities.entity.DistConfigEntity;
import com.zonhar.autofeed.service.DistConfigService;
import com.zonhar.autofeed.service.SensorService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

@Service
public class HcsrTask {

    private final static Logger log = LoggerFactory.getLogger(HcsrTask.class);

    // 传感器休眠时间
    private final static int WAIT_DURATION_IN_MILLIS = 12000;

    @Autowired
    private DistConfigService distConfigService;

    @Autowired
    private RedisUtil redisUtil;

    @Async
    public void csrRun(GpioPinDigitalOutput sensorTrigger,GpioPinDigitalInput sensorResult) {
        log.info("超声波测距传感器开始探测。");
        RangeSensor rangesensor = new RangeSensor(sensorTrigger, sensorResult);
        //发送邮件
        DistConfigEntity propHc = getHcDistConfig("propHc");
        DistConfigEntity warnMax = getHcDistConfig("warnMax");
        DistConfigEntity warnMin = getHcDistConfig("warnMin");
        log.info("传感器参数：{} ,{} ,{}", JSON.toJSONString(propHc),JSON.toJSONString(warnMax),JSON.toJSONString(warnMin));
            try {
                if(true){
                    double distance = rangesensor.getRange();
                    log.info("超声波测距探测到目标距离：{} cm",distance);
                    if(distance >= 8 && distance <= 25){
                        String fileName ="rp-" + DateUtil.format(new Date(), "yyyy-MM-dd") + System.currentTimeMillis() + ".png";
                        //捕抓图像
                        String url = CameraDevice.takeBufferedStill("/Users/zonhar/Desktop", fileName);
                        String tel = tel(url);
                        //推送消息
                        MailUtil.send(getSendEmail(),"猫粮自动投喂机通知",tel,true);
                        log.info("超声波测距传感器邮件推送成功");
                        Map<String,Object> map = MapUtil.newHashMap();
                        map.put("date",System.currentTimeMillis());
                        redisUtil.set("HCSR-04-KEY",JSON.toJSONString(map),60*2);

                    }
                }
            }catch (Exception e){
                log.error("超声波测距传感器异常：{}",e.getMessage());
            }
        }
    private DistConfigEntity getHcDistConfig(String field){
        QueryWrapper<DistConfigEntity> queryWrapper =new QueryWrapper<>();
        queryWrapper.eq("dist_group","hc_sr04");
        queryWrapper.eq("dist_name",field);
        return distConfigService.getOne(queryWrapper);
    }

    /**
     * 获取收件人
     * @return
     */
    private String getSendEmail(){
        QueryWrapper<DistConfigEntity> queryWrapper =new QueryWrapper<>();
        queryWrapper.eq("dist_name","email");
        queryWrapper.eq("dist_group","params");
        DistConfigEntity configEntity = distConfigService.getOne(queryWrapper);
        return configEntity.getDistValue();
    }

    private static String tel(String url){
        String sb = "<div>" +
                "<h1>暖暖疑似正在进食</h1>" +
                "<img src='" + url + "' alt='未知错误' />" +
                "</div>";
        return sb;
    }

}
